package top.iuna.jxls.core.util;

import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 文件名工具类
 * 
 * @author Cheney.Sun
 * @time 2018-04-07
 */
@Slf4j
public class FileNameKit {

  private FileNameKit() {}


  /**
   * 为待下载文件的文件名编码,协助解决各种浏览器下载文件的中文文件名乱码问题
   */
  public static String httpEncode(HttpServletRequest request, String exportFileName) {
    if (null == request || StringUtils.isBlank(exportFileName)) {
      return null;
    }

    String theFinalName = exportFileName;
    // 文件名字节长度限制(某些浏览器如IE,在Response的Header中的长度限制在150字节左右,即如果是中文字符则不能超过16个)
    if (exportFileName.length() > 16) {
      theFinalName = exportFileName.substring(0, 16);
    }

    try {
      String userAgent = request.getHeader("USER-AGENT");
      if (userAgent != null && userAgent.toLowerCase().indexOf("applewebkit") <= -1) {
        theFinalName = URLEncoder.encode(theFinalName, "UTF-8");
      } else {
        theFinalName = new String(theFinalName.getBytes("UTF-8"), "ISO8859-1");
      }
    } catch (Exception e) {
      log.error("FileNameKit#httpEncode error:", e);
      theFinalName =
          String.valueOf(System.currentTimeMillis()) + "." + StringUtils.substringAfterLast(theFinalName, ",");;
    }

    return theFinalName;
  }



}
